/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets.gp.medication;

import be.ugent.medirem.logic.MedicationRemote;
import be.ugent.medirem.persistence.entity.details.MedicationDetails;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Simon
 */
public class MedicationServlet extends HttpServlet {
    @EJB
    private MedicationRemote medicationBean;

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        request.getSession().removeAttribute("pid");
        List<MedicationDetails> list = medicationBean.getAllMedications();
        Collections.sort(list, new Comparator<MedicationDetails>() {

            public int compare(MedicationDetails o1, MedicationDetails o2) {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }

        });
        request.setAttribute("medications", list);
        request.getRequestDispatcher("/gp/medication/list.jsp").forward(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        String query = request.getParameter("query");
        if (query == null || query.isEmpty()) {
            doGet(request, response);
            return;
        }
        List<MedicationDetails> list = medicationBean.searchMedication(query);
        Collections.sort(list, new Comparator<MedicationDetails>() {

            public int compare(MedicationDetails o1, MedicationDetails o2) {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }

        });
        request.setAttribute("query", query);
        request.setAttribute("medications", list);
        request.getRequestDispatcher("/gp/medication/list.jsp").forward(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }

}
